import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:mybaseplus/base/tool/empty/FFEmpty.dart';
import 'package:mybaseplus/base/tool/globalMethod/FFSafeValue.dart';
import 'package:mybaseplus/base/tool/language/baseLanguage/objs/ILanguage.dart';
import 'package:mybaseplus/base/tool/language/baseLanguage/objs/en.dart';
import 'package:mybaseplus/base/tool/language/baseLanguage/objs/zh_Hans.dart';
import 'package:mybaseplus/base/tool/language/baseLanguage/objs/zh_Hant.dart';
import 'package:mybaseplus/base/tool/pprint/FFLog.dart';
import 'package:mybaseplus/base/tool/sp/FFSpUtils.dart';

import '../FFMultiLanguage.dart';

///多语言类
class FFBaseLocale {
  final Locale locale;
  ILanguage language;

  FFBaseLocale(this.locale, this.language);

  static FFBaseLocaleDelegate? delegate;

  ///新增语言这儿要加相应的子类
  static Map<String, ILanguage> map = {
    "end": en(),
    "zh-Hans": zh_Hans(),
    "zh-Hant": zh_Hant(),
  };

  static initDelegate() {
    FFBaseLocale.delegate = FFBaseLocaleDelegate();
  }

  static FFBaseLocale? of(BuildContext context) {
    return Localizations.of(context, FFBaseLocale);
  }
}

///多语言代理类
class FFBaseLocaleDelegate extends LocalizationsDelegate<FFBaseLocale> {
  @override
  bool isSupported(Locale locale) {
    List<String> list = [];
    for (int i = 0; i < FFMultiLanguage.supportedLocalesList.length; i++) {
      LanguageConfigEntity entity = FFMultiLanguage.supportedLocalesList[i];
      if (!list.contains(entity.locale.languageCode)) {
        list.add(entity.locale.languageCode);
      }
    }
    return list.contains(locale.languageCode);
  }

  //加载自定义资源 转成Model
  @override
  Future<FFBaseLocale> load(Locale locale) async {
    String languageCode = locale.languageCode;
    String? scriptCode = locale.scriptCode;

    String addScriptCode = "";
    if (!FFEmpty.stringIsEmpty(scriptCode)) {
      addScriptCode = "$CODELINE$scriptCode";
    }

    ILanguage? language = globalSafeValueFromMap<ILanguage>(FFBaseLocale.map, "$languageCode$addScriptCode") ?? en();
    return SynchronousFuture<FFBaseLocale>(FFBaseLocale(locale, language));
  }

  @override
  bool shouldReload(LocalizationsDelegate<FFBaseLocale> old) {
    return false;
  }
}
